﻿@*//******************************************************************************************************
//  MeterDisturbancesByLine.cshtml - Gbtc
//
//  Copyright © 2017, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
//  not use this file except in compliance with the License. You may obtain a copy of the License at:
//
//      http://opensource.org/licenses/MIT
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  01/10/2017 - Billy Ernest
//       Generated original version of source code.
//
//*******************************************************************************************************@

@using System.Collections.Specialized
@using GSF.Data.Model
@using GSF.Web.Model
@using PQDashboard.Model
@model AppModel
@{
    Layout = "";
    DataContext dataContext = Model.DataContext;

    NameValueCollection parameters = Request.QueryString;

    int postedEventId = int.Parse(parameters["eventid"] ?? "-1");
    EventView theEvent = dataContext.Table<EventView>().QueryRecords(restriction: new RecordRestriction("ID = {0}", postedEventId)).First();
    string context = parameters["context"] ?? "day";

}

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" style="height: 100%;">
<head id="Head1">
    <title>MeterDisturbancesByLine</title>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <meta http-equiv="cache-control" content="max-age=0" />
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="expires" content="0" />
    <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
    <meta http-equiv="pragma" content="no-cache" />

    <link rel="shortcut icon" type="image/ico" href="~/favicon.ico" />
    <link rel="stylesheet" href="~/Content/bootstrap/theme.css" />
    <link rel="stylesheet" type="text/css" href="~/Content/font-awesome.css" />
    <link rel="stylesheet" href="~/Content/bootstrap-3.3.2.min.css" />
    <link rel="stylesheet" href="~/Content/themes/redmond/jquery-ui.css" />
    <link rel="stylesheet" href="~/Scripts/PrimeUI/primeui.min.css" />
    <link rel="stylesheet" href="~/Content/MeterEventsByLine.css" type="text/css" />

    <script type="text/javascript" src="~/Scripts/jquery-2.1.1.js"></script>
    <script type="text/javascript" src="~/Scripts/jquery-ui.js"></script>
    <script src="~/Scripts/jquery.signalR-2.2.0.js"></script>
    <script type="text/javascript" src="~/Scripts/jquery.blockUI.js"></script>
    <script type="text/javascript" src="~/Scripts/bootstrap-3.3.2.min.js"></script>
    <script type="text/javascript" src="~/Scripts/PrimeUI/primeui.js"></script>
    <script src="~/signalr/hubs"></script>
    <script type="text/javascript" src="~/Scripts/Site.js"></script>
    <script type="text/javascript" src="~/Scripts/jstorage.js"></script>
    <script type="text/javascript" src="~/Scripts/moment.js"></script>

</head>

<body style="height: 100%;">
<div class="gridheader"><center>Events for @theEvent.MeterName for @theEvent.StartTime</center>
</div>


<div style="height: 100%; width: 100%;">
    <div style="height: 100%; display: inline-block" id="MeterDetailsByDate"></div>
</div>

<!-- Modals -->
<div id="notesModal" class="modal fade" role="dialog">
    <div class="modal-dialog" style="width: 50%">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Add a note to event record <span id="eventId"></span></h4>
            </div>
            <div id="previousNotesDiv">

            </div>
            <div class="modal-body">
                <textarea wrap="hard" id="note" class="form-control"></textarea>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="saveNote()">Add Note</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>

    </div>
</div>

<script>

    var postedMeterId = "@theEvent.MeterID";
    var postedDate = "@theEvent.StartTime";
    var postedMeterName = "@theEvent.MeterName";
    var context = "@context";
    var disabledList = $.jStorage.get('disabledList');
    var disabledArray = Object.keys(disabledList.Disturbances).map(function (o) { if (!disabledList.Disturbances[o]) return o }).filter(function (val) { return val !== undefined; });
    var userId = "@HttpUtility.JavaScriptStringEncode(ViewBag.username)"

    reconnectHub = false;

    $(document).ready(function () {
        $(window).on('hubConnected', function () {
            populateMeterEventsDivWithGrid('getSiteLinesDetailsByDate', "MeterDetailsByDate", postedMeterName, postedMeterId, postedDate);
        })

    });

    var floatrenderer = function (row, columnfield, value, defaulthtml, columnproperties, rowdata) {

        return '<div style="text-align: center; margin-top: 5px;">' + parseFloat(value).toFixed(4) + "m" + '</div>';

    }

    var columnsrenderer = function (value) { return '<div style="text-align: center; margin-top: 5px;">' + value + '</div>'; };

    function populateMeterEventsDivWithGrid(thedatasource, thediv, siteName, siteID, theDate) {
        dataHub.getSiteLinesDetailsByDate(siteID, theDate, context, 'Disturbance').done(function (data) {
            json = data;

            $.each(json, function (_, obj) {
                obj.voltage = Number(obj.voltage);
                obj.thecurrentdistance = Number(obj.thecurrentdistance);
            });

            $.each(json, function (_, obj) {
                obj.voltage = Number(obj.voltage);
                obj.SeverityCode = Number(obj.SeverityCode);
                obj.magnitude = Number(obj.magnitude);
                obj.duration = Number(obj.duration);
            });

            var filterList = [];

            $.each(json, function (_, element) {
                if (disabledArray.indexOf(element.SeverityCode.toString()) >= 0)
                    filterList.push(element);
            });


            $('#' + thediv).puidatatable({
                scrollable: true,
                scrollHeight: '100%',
                scrollWidth: '100%',
                sortMode: 'multiple',
                sortMeta: [{ field: 'theinceptiontime', order: 1 }],
                columns: [
                    { field: 'thelinename', headerText: 'Line Name', headerStyle: 'width: 9%', bodyStyle: 'width: 9%; height: 20px', sortable: true },
                    { field: 'voltage', headerText: 'Line KV', headerStyle: 'width:  6%', bodyStyle: 'width: 6%; height: 20px', sortable: true },
                    { field: 'theinceptiontime', headerText: 'Start Time', headerStyle: 'width: 30%', bodyStyle: 'width: 30%; height: 20px', sortable: true },
                    { field: 'SeverityCode', headerText: 'Severity', headerStyle: 'width: 9%', bodyStyle: 'width: 9%; height: 20px', sortable: true },
                    { field: 'disturbancetype', headerText: 'Disturbance Type', headerStyle: 'width: 9%', bodyStyle: 'width: 9%; height: 20px', sortable: true },
                    { field: 'phase', headerText: 'Phase', headerStyle: 'width: 9%', bodyStyle: 'width: 9%; height: 20px', sortable: true },
                    { field: 'magnitude', headerText: 'Magnitude (pu)', headerStyle: 'width: 9%', bodyStyle: 'width: 9%; height: 20px', sortable: true },
                    { field: 'duration', headerText: 'Duration (s)', headerStyle: 'width: 9%', bodyStyle: 'width: 9%; height: 20px', sortable: true },
                    { headerText: '', headerStyle: 'width: 4%', content: function (row) { return makeOpenSEEButton_html(row); } },
                    { headerText: '', headerStyle: 'width: 3%', content: function (row) { return makeNoteButton_html(row); } }

                ],
                datasource: filterList
            });
        });
    }


    function makeOpenSEEButton_html(id) {
        var args =
            id.theeventid + ',' +
            id.startmillis + ',' +
            id.endmillis;

        var return_html = "";
        return_html += '<button onClick="OpenWindowToOpenSEE(' + args + ');" title="Launch OpenSEE Waveform Viewer">';
        return_html += '<img src="@Html.Raw(Url.Content("~/Images/seeButton.png"))" /></button>';
        return (return_html);
    }

    function makeNoteButton_html(id) {
        var return_html = "";
        return_html += '<button><span onclick="openNoteModal(' + id.theeventid + ')" class="glyphicon glyphicon-pencil"></span></button>';
        return (return_html);
    }

    var childWindows = { };

    function OpenWindowToOpenSEE(id, highlightStart, highlightEnd) {
        var title = id + "openSEE";

        window.Highlight = {
            Start: highlightStart,
            End: highlightEnd
        };

        if (!childWindows[title] || childWindows[title].closed)
            window.open("@Html.Raw(Url.Content("~/Main/OpenSEE"))?eventid=" + id + "&faultcurves=1", title);
        else
            childWindows[title].UpdateMarkings();

        return false;
    }

    function openNoteModal(eventId) {
        $('#previousNotes').remove();
        dataHub.getNotesForEvent(eventId).done(function (data) {
            $('#eventId').text(eventId);
            if (data.length > 0)
                $('#previousNotesDiv').append('<table id="previousNotes" class="table" ><tr><th style="width: 50%">Note</th><th style="width: 20%">Time</th><th style="width: 20%">User</th><th style="width: 10%"></th></tr></table>')
            $.each(data, function (i, d) {
                $('#previousNotes').append('<tr id="row' + d.ID + '"><td id="note' + d.ID + '" style="word-break:break-all;">' + d.Note + '</td><td>' + moment(d.TimeStamp).format("MM/DD/YYYY HH:mm:ss") + '</td><td>' + d.UserAccount + '</td><td><button onclick="editNote(' + d.ID + ')"><span class="glyphicon glyphicon-pencil" title="Edit this note.  Ensure you save after pushing this button or you will lose your note."></span></button><button onclick="removeNote(' + d.ID + ')"><span class="glyphicon glyphicon-remove" title="Remove this note"></span></button></td></tr>');
            });

            $('#note').val('');
            $('#notesModal').modal('show');
        });

    }
    function saveNote() {
        dataHub.saveNoteForEvent($('#eventId').text(), $('#note').val(), userId).done(function () {
            dataHub.getNotesForEvent($('#eventId').text()).done(function (data) {
                $('#previousNotes').remove();
                $('#noteCount').text(data.length);
                if (data.length > 0)
                    $('#previousNotesDiv').append('<table id="previousNotes" class="table" ><tr><th style="width: 50%">Note</th><th style="width: 20%">Time</th><th style="width: 20%">User</th><th style="width: 10%"></th></tr></table>')
                $.each(data, function (i, d) {
                    $('#previousNotes').append('<tr id="row' + d.ID + '"><td id="note' + d.ID + '" style="word-break:break-all;">' + d.Note + '</td><td>' + moment(d.TimeStamp).format("MM/DD/YYYY HH:mm:ss") + '</td><td>' + d.UserAccount + '</td><td><button onclick="editNote(' + d.ID + ')"><span class="glyphicon glyphicon-pencil" title="Edit this note.  Ensure you save after pushing this button or you will lose your note."></span></button><button onclick="removeNote(' + d.ID + ')"><span class="glyphicon glyphicon-remove" title="Remove this note"></span></button></td></tr>');
                });

                $('#note').val('');
                $('#notesModal').modal('show');
            });

        });
    }

    function removeNote(id) {
        dataHub.removeEventNote(id);
        $('#row' + id).remove();
        $('#noteCount').text(parseInt($('#noteCount').text()) - 1);
    }

    function editNote(id) {
        $('#note').val($('#note' + id).text());
        $('#row' + id).remove();

        dataHub.removeEventNote(id);
    }


</script>

</body>
</html>


